# -*- coding: UTF-8 -*-
# cython: language_level=3
import pymongo
import requests

IP = '173.46.24.2'
PORT = 2000
DB = 'proxy_save'


class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_inst'):
            cls._inst = super(Singleton, cls).__new__(cls, *args, **kwargs)

        return cls._inst


class ProxyDB(Singleton):
    def __init__(self, ip=IP, port=PORT, db=DB):
        super(ProxyDB, self).__init__()

        if not hasattr(self, '_db'):
            try:
                client = pymongo.MongoClient(f"mongodb://root:pattek_123456@{ip}:{port}/")
                self._db = client[db]
            except Exception as e:
                raise
            else:
                print('连接到数据库 %s' % db)

    def get_proxy(self):
        return list(self._db['proxy_hunbo'].aggregate([{'$sample': {'size': 10}}]))[0]['ip']


def get_proxy():
    # try:
    #     proxy = ProxyDB().get_proxy()
    #     assert proxy
    # except:
    #     return {'http': proxy, 'https': proxy}
    return None


def check_proxy(proxy):
    error_flag = 3
    for i in range(3):
        try:
            proxies = {'http': proxy, 'https': proxy}
            print(proxies)
            status_code = requests.head('https://www.baidu.com/', proxies=proxies, timeout=(2.1, 3.1)).status_code
            assert status_code == 200
            break
        except Exception as e:
            print('error', e)
            error_flag -= 1

    return error_flag


if __name__ == '__main__':
    for i in range(30):
        proxy = ProxyDB().get_proxy()
        # proxy = {'http': proxy, 'https': proxy} if proxy else None
        # print(proxy)
        print(check_proxy(proxy))
